package PrjConf

import (
	"dgo/goutils/proj"
	"dgo/goutils/utils"
	"flag"
	"fmt"
	"gitee.com/ymofen/supervalue"
	"os"
	"time"
)

var (
	AppConf   *wrapper.SuperValue
	localConf *wrapper.SuperValue
	logger    utils.ILogger

	cmdflag_configfile *string
	cmdflag_uuidfile   *string
	cmdflag_uuid       *string
)

func StartProj() {
	utils.SetFatalRec("")
	logger = proj.CreateAppLogger()

}

func StartProjWithoutFataLog() {
	logger = proj.CreateAppLogger()
}

func DefaultLoggerStatus() string {
	if logger == nil {
		return "DefaultLog is nil"
	} else {
		if sf, ok := logger.(*utils.SafeLogger); ok {
			return fmt.Sprintf("%s", sf.Status())
		} else {
			return "DefaultLogger is not safelogger"
		}
	}
}

func DeferProjWithoutFataLog() {
	if logger != nil {
		logger.Close()
	}
}

func DeferProj() {
	utils.DeferFatalRec()
	if logger != nil {
		logger.Close()
	}
}

func WaitForAppExit() {
	for {
		time.Sleep(time.Second)
	}
}

func LoadConfigFromAnyWhere() *wrapper.SuperValue {

	err, conf := ReloadApiSvrConfByCmd()
	if err != nil {
		utils.Log.Warnf("加载API配置出现异常:%s", err.Error())
	} else if conf != nil {
		AppConf = conf
		return conf
	}

	conf = ReloadConfigFileFromStartup()

	if conf == nil {
		conf = ReloadConfigFromLocal()
		AppConf = conf
		localConf = conf
	}

	return conf
}

func MakeAppUUIDEncryptString(idstr string) string {
	fileBuf := utils.Encrypt("D10"+idstr, "uuid")
	return fileBuf
}

func MakeAppUUIDByUUIDFile(APP_TYPE, prefix, uuidfile string, idlen int) string {
	if len(uuidfile) == 0 {
		uuidfile = "app.uuid"
	}
	var idstr string
	buf, _ := utils.ReadFile(uuidfile)
	if len(buf) > 0 {
		fileStr := string(buf)
		idstr = utils.Decrypt(fileStr, "uuid")

		if len(idstr) > 3 && idstr[0] == 'D' && idstr[1] == '1' && idstr[2] == '0' {
			idstr = idstr[3:]
			if len(idstr) == idlen || idlen <= 0 {
				var sb utils.BytesBuilder
				if len(APP_TYPE) > 0 {
					sb.AppendStr(APP_TYPE).AppendStr("-")
				}
				if len(prefix) > 0 {
					sb.AppendStr(prefix).AppendStr("-")
				}
				sb.AppendStr(idstr)

				return sb.String()
			}
		}
	}

	if idlen <= 0 {
		idstr = utils.RandHexString(6)
	} else {
		idstr = utils.RandHexString(idlen)
	}
	fileBuf := MakeAppUUIDEncryptString(idstr)
	err := utils.RewriteFile(uuidfile, []byte(fileBuf))
	if err != nil {
		fmt.Fprintf(os.Stderr, "uuid write %s err", uuidfile)
	}
	var sb utils.BytesBuilder
	if len(APP_TYPE) > 0 {
		sb.AppendStr(APP_TYPE).AppendStr("-")
	}
	if len(prefix) > 0 {
		sb.AppendStr(prefix).AppendStr("-")
	}
	sb.AppendStr(idstr)
	return sb.String()

}

func MakeAppUUIDByStartupArgs(prefix string) {
	if cmdflag_uuid != nil && len(*cmdflag_uuid) > 0 {
		APP_UUID = *cmdflag_uuid
		return
	}
	if cmdflag_uuidfile != nil && len(*cmdflag_uuidfile) > 0 {
		APP_UUID = MakeAppUUIDByUUIDFile(APP_TYPE, prefix, *cmdflag_uuidfile, 0)
		return
	}
	APP_UUID = utils.Trim(MakeAppId(APP_TYPE, prefix))
}

func MakeAppUUIDByAnyConf(prefix string) {
	APP_UUID = MakeAppId(APP_TYPE, prefix)
}

func CmdFlagPrepareUUIDFile() {
	cmdflag_uuidfile = flag.String("uuidfile", "", "")
	cmdflag_uuid = flag.String("app-uuid", "", "")
}

func CmdFlagPrepareUUIDFileFunc(cmd *utils.FlagSet) {
	cmdflag_uuidfile = cmd.String("uuidfile", "", "")
	cmdflag_uuid = cmd.String("app-uuid", "", "")
}

func CmdFlagPrepareConfigFile() {
	cmdflag_configfile = flag.String("configfile", "", "")
}

func ReloadConfigFileFromStartup() *wrapper.SuperValue {
	if cmdflag_configfile != nil && len(*cmdflag_configfile) > 0 {
		if !utils.FileIsExists(*cmdflag_configfile) {
			fmt.Fprintf(os.Stderr, "配置文件[%s]不存在", *cmdflag_configfile)
			return nil
		}
		rval := ReloadConfigFromAFile(*cmdflag_configfile)
		return rval
	} else {
		return nil
	}
}

func ReloadConfigFromLocalFromFile(filename string) bool {
	if !utils.FileIsExists(filename) {
		return false
	}

	conf := ReloadConfigFromAFile(filename)
	if conf != nil {
		localConf = conf
		utils.Log.Infof("加载配置文件成功:%s", filename)
		return true
	}
	return false
}

func ReloadConfigFromLocal() *wrapper.SuperValue {
	strName := utils.ExtractFileNameWithOutPathAndExt(os.Args[0]) + ".config.json"
	if ReloadConfigFromLocalFromFile(strName) {
		return localConf
	}

	strName += utils.GetExecuteFileDirectory() + utils.PathSeparator + strName
	if ReloadConfigFromLocalFromFile(strName) {
		return localConf
	}

	strName = "app.config.json"
	filename := utils.GetExecuteFileDirectory()
	filename += utils.PathSeparator + strName
	if ReloadConfigFromLocalFromFile(filename) {
		return localConf
	}

	filename = utils.GetExecuteFileDirectory() + utils.PathSeparator + "config" + utils.PathSeparator + strName
	if ReloadConfigFromLocalFromFile(filename) {
		return localConf
	}

	filename = "config" + utils.PathSeparator + strName
	if ReloadConfigFromLocalFromFile(filename) {
		return localConf
	}

	filename = strName
	if ReloadConfigFromLocalFromFile(filename) {
		return localConf
	}

	return nil
}

func ReloadConfigFromAFile(filename string) *wrapper.SuperValue {
	conf, err := wrapper.NewSVFromFile(filename)
	if err != nil {
		utils.Log.Errf("加载配置文件[%s]出现异常:%s", filename, err.Error())
		return nil
	}
	return conf
}
